import java.io.*;
import java.util.*;

public class Manager 
{
	public int state;
	public static final int POLICE_MIN_TO_CATCH_THIEF = 3;
	public List<Agent> polices = new LinkedList<Agent>();
	public List<Agent> thieves = new LinkedList<Agent>();

	public List<PID> cities = new ArrayList<PID>();

	public Manager() {
		loadCityConf();
	}

	public void registerAgent(Agent agent) {
		if (isPolice(agent)) {
			polices.add(agent);
		} else if (isThief(agent)) {
			thieves.add(agent);
		}
	}

	public void unregisterAgent(Agent agent) {
		if (isPolice(agent)) {
			polices.remove(agent);
		} else if (isThief(agent)) {
			thieves.remove(agent);
		}
	}

	private void catchChief() {
		if (hasThief() && hasEnoughPolices() )
		{
			//catch the thief
		}
	}

	public Agent findAgentByID(int id) {
		ListIterator<Agent> iterator = polices.listIterator();
		Agent agent = null;
		while (iterator.hasNext()) {
			agent = iterator.next();
			if (agent.getID()==id)
				return agent;
		}

		iterator = thieves.listIterator();
		while (iterator.hasNext()) {
			agent = iterator.next();
			if (agent.getID()==id)
				return agent;
		}

		return null;
	}

	public boolean hasThief() {
		return thieves.size()>0;
	}

	public boolean hasEnoughPolices() {
		return polices.size()>=Manager.POLICE_MIN_TO_CATCH_THIEF;
	}

	//is a police?
	private boolean isPolice(Agent agent) {
		return agent.getType() == Agent.TYPE_POLICE;
	}

	private boolean isThief(Agent agent) {
		return agent.getType()==Agent.TYPE_THIEF;
	}

	public static void test() {
		Manager m = new Manager();
        System.out.println("------cities-------");
		PID pid = null;
		for (int i=0;i<m.cities.size();i++){
			pid = m.cities.get(i);
			System.out.println(pid.getName()+" "+pid.getIP());
		}
        System.out.println("------end-------");


		Agent a1 = new Agent("P1",1);
		Behaviour pb1 = new PoliceBehaviour(a1);
		a1.setBehaviour(pb1);

		
		Agent a2 = new Agent("P2",2);
		Behaviour pb2 = new PoliceBehaviour(a2);
		a2.setBehaviour(pb2);

		System.out.println(m.polices.size());
		m.registerAgent(a1);
		System.out.println(m.polices.size());
		m.registerAgent(a2);
		System.out.println(m.polices.size());
		m.unregisterAgent(a1);
		System.out.println(m.polices.size());
		m.unregisterAgent(a2);
		System.out.println(m.polices.size());
	}

	public static void main(String [] args) {
		Manager.test();
	}

	private void loadCityConf() {
		BufferedReader in = null;
		try{
			in = new BufferedReader(
					new InputStreamReader(
						new FileInputStream("city.conf")));
			String line;
		   while ( (line=in.readLine()) != null) {
			   String[] fmt = line.split(" ");
			   cities.add(new PID(fmt[0],fmt[1]));
		   }
		}catch(IOException ex) {
			System.out.println(ex);
		}finally {
			try{
				if (in!=null)
					in.close();
			}catch(IOException ex) { }
		}
	}

	public PID getRandomCity() {
		int index = new Random().nextInt(cities.size());
		return cities.get(index);
	}
}
